# coding=utf-8
from django.shortcuts import render
from blog.models import Article
from  django.db.models import Q
from django.http import  HttpResponse


def index(request):
    articles = Article.objects.all()
    return render(request, 'index.html', {'articles': articles})


def article_page(request, article_id):
    article = Article.objects.get(pk=article_id)
    return render(request, 'article_page.html', {'article': article})

#
# #提交数据模板
# def edit_page(request):
#     return  render(request,'edit_page.html')
#
#
# def edit_action(request):
#     title = request.POST.get('title','TITLE')
#     content = request.POST.get('content','CONTENT')
#     Article.objects.create(title=title, content=content)
#     articles = Article.objects.all()
#     return render(request, 'index.html', {'articles': articles})


#提交数据成功
def edit_page(request, article_id):
    if str(article_id) == '0':
        return render(request, 'edit_page.html')
    article = Article.objects.get(pk=article_id)
    return render(request, 'edit_page.html', {'article': article})


def edit_action(request):
    title = request.POST.get('title', 'TITLE')
    content = request.POST.get('content', 'CONTENT')
    article_id = request.POST.get('article_id', 0)

    if int(article_id):
        article = Article.objects.get(pk=article_id)
        article.title = title
        article.content = content
        article.save()
    else:
        Article.objects.create(title=title, content=content)
    articles = Article.objects.all()
    return render(request, 'index.html', {'articles': articles})


def delete(request, article_id):
    Article.objects.get(pk=article_id).delete()
    articles = Article.objects.all()
    return render(request, 'index.html', {'articles': articles})


def search_action(request):
    keyword = request.POST.get('content')
    query_dict = (Q(title__icontains=keyword)|Q(content__icontains=keyword))
    articles = Article.objects.filter(query_dict)
    return render(request, 'index.html', { 'articles': articles, })
#
# def modify(request,article_id):
#     # article_id = request.GET.get('id')
#     article_obj = Article.objects.get(id=article_id)
#     return render(request,'edit_page.html',{'article_obj':article_obj})
#
#
# def modify_res(request):
#     # id = request.POST.get('id')
#     title = request.POST.get('title')
#     content = request.POST.get('content')
#     article_obj = Article.objects.get('content')
#     article_obj.title = title
#     article_obj.content = content
#     article_obj.save()
#     return render(request, 'index.html', {'articles': article_obj})






